# {
#     "empExtKey": "105",
#     "empUCode": 5087556,
#     "modifyTime": "2023-03-28 01:16:59.0"
# }
from module.huada.entity.base_entity import BaseEntity
from plugin import MSsqlClient, Mylogger, Config, MyTime

virtual_card_cache = {}


class VirtualCardEntity(BaseEntity):
    url = "tunion/get/onecarduser"
    table_name = "virtualcard"
    api_data_list = []
    create_table = True
    get_time = "2000-01-01 00:00:00"
    order_by = "modifyTime"
    sync_list = []
    write_back_dict = {}

    def __init__(self, **kwargs) -> None:
        self.empExtKey = kwargs.get('empExtKey')  # 人员主键
        self.empUCode = kwargs.get('empUCode')  # 人员虚拟编号
        self.modifyTime = kwargs.get('modifyTime')
        self.isdeal = kwargs.get('isdeal') or 0  # 是否处理过，0未处理，1已处理, -n 代表第n次处理失败
        self.id = kwargs.get('id') or 0

    @classmethod
    def do_sync(cls, client: MSsqlClient, objs):
        """
        虚拟卡只做缓存，不做数据库操作
        重复的记录，后面得到的记录会覆盖前面的记录
        前面的记录会被标记为已处理
        """
        for obj in objs:
            if not virtual_card_cache.__contains__(obj.empExtKey):
                virtual_card_cache[obj.empExtKey] = obj
            else:
                if virtual_card_cache[obj.empExtKey].modifyTime != obj.modifyTime:
                    old_obj = None
                    new_obj = None
                    cache_time = virtual_card_cache[obj.empExtKey].modifyTime
                    diff = int(MyTime.timestampfrom(obj.modifyTime)) - int(MyTime.timestampfrom(cache_time))
                    old_obj = virtual_card_cache[obj.empExtKey] if diff > 0 else obj
                    new_obj = virtual_card_cache[obj.empExtKey] if diff < 0 else obj
                    # Mylogger.info(f"虚拟卡号{obj.empExtKey}的员工编号发生变化，原编号{old_obj.empUCode}，新编号{new_obj.empUCode}")
                    virtual_card_cache[obj.empExtKey] = new_obj

                    key = 1
                    if not cls.write_back_dict.__contains__(str(key)):
                        cls.write_back_dict[str(key)] = []

                    cls.write_back_dict[str(key)].append(str(old_obj.id))

        return super().do_sync(client, objs)
